﻿using System;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Configuration.Json;

namespace com.uplus.common
{
    public static class AppConfigurtaion
    {
        public static IConfiguration Configuration { get; set; }
        static AppConfigurtaion()
        {
            Configuration = new ConfigurationBuilder()
            .Add(new JsonConfigurationSource { Path = "appsettings.json", ReloadOnChange = true })
            .Build();
        }

        public static string GetFirstSection(string key)
        {
            return Configuration[key];
        }

        public static T GetFirstSection<T>(string key)
        {
            object re = null;
            try
            {
                re = Configuration[key];
                re = Convert.ChangeType(re, typeof(T));
            }
            catch
            {
                re = default(T);
            }
            return (T)re;
        }

        public static string GetSecondSection(string firstNode, string secondNode)
        {
            return Configuration[$"{firstNode}:{secondNode}"];
        }

        public static T GetSecondSection<T>(string firstNode, string secondNode)
        {
            object re = null;
            try
            {
                re = Configuration[$"{firstNode}:{secondNode}"];
                re = Convert.ChangeType(re, typeof(T));
            }
            catch
            {
                re = default(T);
            }
            return (T)re;
        }

        /// <summary>
        /// 获取ConnectionStrings下指定key的节点值(Shorthand for GetSection("ConnectionStrings")[name])
        /// </summary>
        /// <param name="key">子节点key</param>
        /// <returns>返回ConnectionStrings下的子节点</returns>
        public static string GetConnectionString(string key)
        {
            return Configuration.GetConnectionString(key);
        }
    }
}
